define(function (require, exports, module) {
    var $ = require("jquery");
    require("jqtree");
    var angular = require("angular");

    var __seed = 0;

    function genClientUniqueID() {
        return "__" + parseInt(Math.random() * 10000) + "_" + (__seed++);
    }

    angular
        .module('roleTree', [])
        .directive("ngRoleTree", ["$timeout", function ($timeout) {
            return {
                scope: {
                    "roles": "=roles",
                    "selects": "=selects",
                    "multi": "=multi"
                },
                link: function (scope, iEle, iAttr, ctrl) {
                    if (!scope.selects) {
                        scope.selects = [];
                    }

                    if (typeof scope.multi === 'undefined') {
                        scope.multi = true;
                    }

                    var name = "role_cb_" + genClientUniqueID();
                    var $rTree = $(iEle[0])
                        .tree({
                            dragAndDrop: false,
                            useContextMenu: false,
                            selectable: true,
                            autoOpen: 0, //展开级别
                            //创建节点时
                            onCreateLi: function (node, $li) {
                                if (!node.children || node.children.length == 0) {
                                    var id = "role_cb" + node.id + "_" + scope.id + genClientUniqueID();

                                    var html;
                                    if (scope.multi) {
                                        html = "<span class='checkbox'><input id='" + id + "' type='checkbox' value='" + node.id + "'><label for='" + id + "'>&nbsp;</label></span>";
                                    } else {
                                        html = "<span class='radio'><input name='" + name + "' id='" + id + "' type='radio' value='" + node.id + "'><label for='" + id + "'>&nbsp;</label></span>"
                                    }

                                    $li
                                        .find(".jqtree-title")
                                        .prepend(html);
                                }
                            },
                            //是否可以移动
                            onCanMove: function (node) {
                                return false;
                            },
                            //是否可以移动到
                            onCanMoveTo: function (moved_node, target_node, position) {
                                //只能在同级节点中移动
                                return false;
                            },
                            //移动句柄
                            onIsMoveHandle: function ($ele) {
                                return false;
                            },
                            onCanSelectNode: function (node) {
                                return !node.children || node.children.length == 0;
                            }
                        })
                        .on("mouseup keyup", function () {
                            $timeout(updateSelect);
                        })
                        .on('click', '.jqtree-element', function (e) {
                            var $item = $(this);

                            var $label = $item.find('label');

                            var target = e.target;

                            var $input = $item.find('input');
                            if ($input[0]) {
                                if (!$.contains($label, target) && $label[0] !== target && $input[0] !== target) {
                                    $input.prop('checked', !$input.prop('checked'));
                                }
                            }
                        });

                    scope.$watch("roles", function (newValue, oldValue) {
                        if (!newValue) {
                            return;
                        }
                        var treeData = fixedData(newValue);

                        $rTree.tree('loadData', treeData);

                        updateSelectView();
                    });

                    function updateSelect() {
                        var selects = [];
                        $rTree.find("input:checked").each(function () {
                            selects.push($(this).val());
                        });
                        scope.selects = selects;
                    }

                    function updateSelectView() {
                        $rTree.find("input[type='checkbox']").prop("checked", false);
                        angular.forEach(scope.selects, function (item) {
                            var node = $rTree.tree("getNodeById", item);
                            if (node) {
                                $(node.element).find("input[type='checkbox']").prop("checked", true);
                            }
                        });
                    }
                }
            };
            function fixedData(allRoles) {
                var data = [];
                data.push({id: "group", name: "集团级角色", children: allRoles.groupRoles});
                data.push({id: "company", name: "公司级角色", children: allRoles.companyRoles});
                return data;
            }
        }])
});